package com.dsx.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsx.commons.result.Result;
import com.dsx.entity.Blog;
import com.dsx.service.BlogService;
import com.dsx.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dsx
 * @since 2021-03-30
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    BlogService blogService;
    //获取所有博客，并分页显示
    @GetMapping("/all")
    public Result getBlogs(@RequestParam(defaultValue = "1") int currentPage){
        int size = 5;
        Page page =new Page(currentPage,size);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        System.out.println(pageData.getTotal());
        return Result.success(pageData);
    }
    //根据id查询博客
    @GetMapping("/{id}")
    public Result detail(@PathVariable int id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"博客不存在");
        return Result.success(blog);
    }
    //修改和添加博客，blog存在id就是修改，不存在id就是删除
    //使用mybatis-plus自动insert对象，对象里不能有null值。
    //基本类型和String比较值用.equals()
    @RequiresAuthentication
    @PostMapping("/edit")
    public Result editBlog(@Validated @RequestBody Blog blog){
        System.err.println("editBlog====blogId:"+blog.getId());
        if(blog.getId()!=null){
            Blog dbBlog = blogService.getById(blog.getId());
            //用户只能编辑属于自己的博客
           Assert.isTrue(dbBlog.getUserId().equals(ShiroUtil.getAccountProfile().getId()),"不能修改别人的博客");
           
           BeanUtil.copyProperties(blog,dbBlog);
            boolean save = blogService.update(dbBlog,new UpdateWrapper<Blog>().eq("id",blog.getId()));
           return Result.success(dbBlog);
       }else {
            Blog temp = new Blog();
            temp.setUserId(ShiroUtil.getAccountProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
            BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
            System.out.println(temp.toString());
            boolean save = blogService.saveOrUpdate(temp);
            return save? Result.success(temp):Result.fail("添加失败");
       }
    } 
    
}
